import React,{Component} from "react";
import {connect} from "react-redux"
import {List,Badge} from "antd-mobile";

const Item = List.Item
const Brief = Item.Brief
//功能函数，对聊天记录进行删选，找到每组聊天记录的最后一条消息
function getLastMsg(chatMsg,me_id) {
    //将聊天记录保存到一个容器中
    const lastMsgObj = {} //保存的结构是{chat_id:{msg}}
    chatMsg.forEach(msg=>{

        //统计未读聊天的数目
        //判断消息未读的条件是to是当前用户，并且read属性值是false
        if (msg.to===me_id&&!msg.read){
            msg.unReadcount = 1
        }else{
            msg.unReadcount = 0
        }

        //先获取当前msg的id
        const chat_id = msg.chat_id
        //先去保存的记录中查找
        const lastMsg = lastMsgObj[chat_id]
        if (!lastMsg){
            //如果还没有记录，那就作为第一条数据
            lastMsgObj[chat_id] = msg
        }else{
            //不是第一条需要更新未读消息的数量
            const unReadcount = lastMsg.unReadcount+msg.unReadcount
            //如果有就比较两条记录的时间，晚的留下
            if (lastMsg.create_time<msg.create_time){
                lastMsgObj[chat_id] = msg
            }
            //这条语句不可以写在上面，因为只能在确定lastmsg之后才可以修改未读消息，不然就被覆盖了
            lastMsgObj[chat_id].unReadcount = unReadcount
        }
    })

    //得到消息数组
    const lastMsgs = Object.values(lastMsgObj) //得到的结构[{from,to ,content;;;},{}]
    //测试
    console.log(lastMsgs)
    //将消息数组进行排序，时间降序排列
    lastMsgs.sort(function (a,b) {//如果是<0就是ab，反之就是ba
        return b.create_time - a.create_time
    })
    //排序之后将最后一条消息的时间计算出来
   /* var minutes = 1000 * 60;
    var hours = minutes * 60;
    var days = hours * 24;
    var years = days * 365;
    const a = Date.parse('2014/12/25 14:03:00'); // => 1419480000000`
    const h = (Math.round(a / hours)%24+8)%24;
    const m = Math.round(a / minutes)%60;*/
    const minutes = 1000 * 60;
    const hours = minutes * 60;
    for (let msg = 0;msg<lastMsgs.length;msg++){
        //测试
        //console.log(lastMsgs[msg]["create_time"])
        const hour = (Math.round(lastMsgs[msg]["create_time"]/ hours)%24+8)%24-1
        const minute = Math.round(lastMsgs[msg]["create_time"] / minutes)%60;
        //console.log(hour,minute)
        //时间小于9加个前置0
        //******************************************************************************************
        //这里有个bug，如果计算出时间直接覆盖掉原来的create_time，页面一刷新时间就错了,所以这里新建一个属性time保存时间，bug不知哪里发生的，为了避免bug就不要直接改create_time
        //*********************************************************************************************
        if (hour<=9){
            if (minute<=9){
                lastMsgs[msg]["time"] = '0'+hour+":"+'0'+minute
            }
            else{
                lastMsgs[msg]["time"] = '0'+hour+":"+minute
            }
        }
        else {
            if (minute<=9){
                lastMsgs[msg]["time"] = hour+":"+'0'+minute
            }
            else{
                lastMsgs[msg]["time"] = hour+":"+minute
            }
        }
    }
    return lastMsgs
}
class Message extends Component{
    render() {
        //debugger
        const {user} = this.props
        const {users,chatMsgs} = this.props.chatmsg
        //防止数据还没请求回来就显示页面导致错误
        if (!user){
            return null
        }
        if (!users){
            return null
        }
        if (!chatMsgs){
            return null
        }
        //先挑选出和当前用户有关的聊天记录，
        const me_id = user._id
        console.log("筛选之前的",chatMsgs)
        const target_chatMsg =getLastMsg(chatMsgs,me_id)
        console.log("筛选之后的msg",target_chatMsg)
        //const tiem = "10:34"
        return(
            <List style={{marginTop:45}}>
                {
                    target_chatMsg.map(msg=>{
                        //函数已经返回了聊天的内容和时间，下面找到用户头像和名字
                        const targetUserId = msg.from===me_id?msg.to:msg.from
                        const targetUser = users[targetUserId]
                        return(
                            <Item
                                key = {msg.chat_id}
                                arrow='horizontal'
                                extra={<div><div>&nbsp;{msg.time}</div><div><Badge text={msg.unReadcount} overflowCount={55}/></div></div>}
                                thumb={require("../../assets/headers/"+targetUser.header+".png")}
                                onClick={()=>this.props.history.push('/chat/'+targetUserId)}
                                >{targetUser.username} <Brief>{msg.content}</Brief>
                            </Item>
                        )
                    })
                }
            </List>
        )
    }
}
export default connect(
    state=>({user:state.user,chatmsg:state.chatmsg}),
    {}
)(Message)
/*
*  <Item
                    arrow='horizontal'
                    extra={<div><div>&nbsp;{tiem}</div><div><Badge text={7} overflowCount={55}/></div></div>}
                    thumb={require("../../assets/headers/头像1.png")}
                >王老板 <Brief>在吗？</Brief>
                </Item>
                <Item
                    arrow='horizontal'
                    extra={<div><div>&nbsp;{tiem}</div><div><Badge text={7} overflowCount={55}/></div></div>}
                    thumb={require("../../assets/headers/头像2.png")}
                >张老板<Brief>我公司给你30k月薪，来我们公司吧！电话：14747430693</Brief></Item>
* */